#!/bin/bash
set -e;
source ../../pi.vars;
alist_version=`get_github_latest https://github.com/alist-org/alist/releases/latest`


project_name='alist'
echo "copy files......"
whoname=`whoami`
sudo mkdir -p /opt/${project_name}/logs;sudo chmod -R 755 /opt/${project_name};
sudo chown -R ${whoname} /opt/${project_name};
if [ -f /opt/${project_name}/data/config.json ];then
	sudo systemctl stop ${project_name}||echo 'skip'
	rm -f /opt/${project_name}/alist-linux-arm64.tar.gz;
fi;
wget ${github_proxy}https://github.com/alist-org/alist/releases/download/v${alist_version}/alist-linux-arm64.tar.gz -O /opt/${project_name}/alist-linux-arm64.tar.gz
tar -xf /opt/${project_name}/alist-linux-arm64.tar.gz -C /opt/${project_name}/;
cp st*.sh /opt/${project_name}/;
cp *.service /opt/${project_name}/;
chmod -R 755 /opt/${project_name}/;

sed -i "s/User=.*/User=${whoname}/g" /opt/${project_name}/${project_name}.service;
sudo cp /opt/${project_name}/${project_name}.service /lib/systemd/system/${project_name}.service;
sudo systemctl daemon-reload;



if [ -e /opt/${project_name}/data/config.json ]; then
    echo "There is having /opt/${project_name}/data/config.json, ignore init alist!"
	echo "start services......"
	sudo systemctl enable --now ${project_name};
	echo "login url: http://ip:port"
else

	echo "input service port(default:5244):"
	read -t 10  input_port;


	echo "start services......"
	sudo systemctl enable --now ${project_name};

	if [ "${input_port}" != "" ];then
		sed -i "s/http_port.*/http_port\": ${input_port},/g" /opt/alist/data/config.json;
		sudo systemctl restart ${project_name};
		sleep 10;
	fi;
	/opt/${project_name}/alist admin set password;

	echo "login url: http://ip:port"
	echo "init admin,pass_info: password"


fi;


